using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using FUSE;


namespace FUSE
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class FUSEgame : Microsoft.Xna.Framework.Game
    {
        //Thread thread;

        int currentScreen = MyConstants.ITitleScreen; // default 0 is titlescreen
        int oldScreen = MyConstants.ITitleScreen;

        //Graphical declarations
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        //Screens
        TitleScreen titleScreen;
        CreationScreen creationScreen;

        Galaxy galaxy;


        
        //private Texture2D backgroundTexture, headTexture;

        //Game declarations
        private Planet planet1;
        private int lastTickCount;
        private KeyboardState keyboard;
        private Player gamePlayer;
        private DemoMapGenerator demoMapGen;
        private MapGenerator mapGenerator;

        public FUSEgame()
        {
            graphics = new GraphicsDeviceManager(this);
            
            Content.RootDirectory = "Content";
            //Debug view debugs our galaxy physics world


        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {

            

            // TODO: Add your initialization logic here
            //TODO:Initialize sound here

            Window.Title = "FUSE Alpha Game";

            // load title screen            
            titleScreen = new TitleScreen(graphics);
            titleScreen.Initialize();

            //load creationscreen
            creationScreen = new CreationScreen(graphics);
            creationScreen.Initialize();

            base.Initialize();
        }
        /// <summary>
        /// 
        /// </summary>
        protected override void BeginRun()
        {
            //TODO: play the title sound here

            //TODO: Start the logo splash screen here
            //ChangeState(GameState.LogoSplash);

            //TODO:field of view
            //TODO: aspect ratio
            //TODO:near plane
            //TODO:farplane

            //TODO: initialize camera here
            //TODO: camera view position
            base.BeginRun();
        }

        /*
        private void LoadContentThread()
        {
            thread = new Thread(new ThreadStart(LoadContentHelper));
            thread.IsBackground = true;
            thread.Start();

            while (!thread.IsAlive) ;
        }
         * */

        private void LoadContentHelper()
        { 
            


            Galaxy galaxy = new Galaxy(this);
            galaxy.Initialize();

            Components.Add(galaxy);

            

            /*
            int arraySize = 1;
            Texture2D[] planets = new Texture2D[arraySize];
            planets[0] = Content.Load<Texture2D>("Planet01Small");

            demoMapGen = new DemoMapGenerator(this);
            demoMapGen.Initialize();
            Map demoMap = demoMapGen.GenerateDemoMap(2);
            demoMap.galaxyForces = PhysicsEngine.createGravityGrid2(demoMap);

            PhysicsEngine.ToStringGalaxy(demoMap, false);

            Console.WriteLine(demoMap.ToString());
             */

            //Galaxy galaxy = new Galaxy();
            //Components.Add(galaxy);

        }
        

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            base.LoadContent();

            //TODO: load services
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            
            Services.AddService(typeof(SpriteBatch), spriteBatch);
            Services.AddService(typeof(GraphicsDeviceManager), graphics);

            demoMapGen = new DemoMapGenerator(this);
            demoMapGen.Initialize();
            Services.AddService(typeof(DemoMapGenerator), demoMapGen);

            mapGenerator = new MapGenerator(this);
            mapGenerator.numberPlanets = 1;
            mapGenerator.numberSuns = 1;
            mapGenerator.numberWormholes = 1;
            mapGenerator.numberBlackholes = 1;
            mapGenerator.Initialize();

            Services.AddService(typeof(MapGenerator), mapGenerator);

            Components.Add(mapGenerator);
            //Create player
            gamePlayer = new Player(this);
            Services.AddService(typeof(Player), gamePlayer);

            Galaxy galaxy = new Galaxy(this);
            galaxy.Initialize();

            Components.Add(galaxy);

            titleScreen.LoadContent(this.Content);
            creationScreen.LoadContent(this.Content);

            

            //LoadContentThread();

            
            

            

            
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }
        Vector2 force = new Vector2(10, 10);
        
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {

            


            //TODO: Add controls here 
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            //update screens
            if (currentScreen == MyConstants.ITitleScreen)
            {
                titleScreen.Update(gameTime);
                UpdateScreenSelection(titleScreen.ScreenSelection);
            }
            else if (currentScreen == MyConstants.ICreationScreen)
            {
                creationScreen.Update(gameTime);
                UpdateScreenSelection(creationScreen.ScreenSelection);
            }
            else if (currentScreen == MyConstants.GalaxyScreen)
            {
                foreach (Galaxy item in Components.OfType<Galaxy>())
                {
                    if (item.ScreenSelection != MyConstants.GalaxyScreen)
                        UpdateScreenSelection(item.ScreenSelection);
                    else
                        item.Enabled = true;
                }
                
            }

            // TODO: Add your update logic here

            //mapGenerator.Update(gameTime);
            /*
            if (thread.IsAlive)
            {
                if (mapGenerator.mapList.Count < 1)
                {
                    thread.Suspend();
                }

                if (mapGenerator.mapList.Count >= 1 && thread.ThreadState == System.Threading.ThreadState.Suspended)
                {
                    thread.Resume();
                }

            }
            **/
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);


            // TODO: Add your drawing code here
            spriteBatch.Begin();

            //draw title screen
            //titleScreen.Draw();

            //draw current screen
            if (currentScreen == MyConstants.ITitleScreen)
            {
                titleScreen.Draw();
            }
            else if (currentScreen == MyConstants.ICreationScreen)
            {
                creationScreen.Draw();
            }
            else if (currentScreen == MyConstants.GalaxyScreen)
            {

                
                foreach (Galaxy item in Components.OfType<Galaxy>())
                {
                    if (item.ScreenSelection != MyConstants.GalaxyScreen)
                        UpdateScreenSelection(item.ScreenSelection);
                    else
                        item.Visible = true;
                }
            }
        

            spriteBatch.End();

            base.Draw(gameTime);
        }

        // checks for screen change request and handles it
        private void UpdateScreenSelection(int screenNumberReturned)
        {
            // if the screen number requested is different than the current screen number
            if (screenNumberReturned != currentScreen)
            {
                currentScreen = screenNumberReturned;
            }
        }
    }
}
